package com.dingding.special.user.validate.dao.impl;

import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.daox.ICriteriaBaseDao;
import com.dingding.common.core.beans.Phonevalidate;
import com.dingding.special.user.validate.dao.IValidateCodeDao;

/**
 * 
 * @ClassName: ValidateCodeDaoImpl 
 * @author CHEHAUNBO 
 * @date 2016年8月23日 下午5:08:30
 * 
 */
@Component("validateCodeDao")
public class ValidateCodeDaoImpl implements IValidateCodeDao {

	private static Logger log = Logger.getLogger(ValidateCodeDaoImpl.class);

	@Resource(name = "criteriaBaseDao")
	private ICriteriaBaseDao criteriaBaseDao;

	/**
	 *
	 * 保存手机验证码到数据库
	 * @Title: saveVliateCode
	 * @param validateCode 验证码
	 * @return true 成功 false 失败
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public boolean saveVliateCode(String telPhone, String validateCode) {

		Criterion criterion = Restrictions.eq("phoneNum", telPhone);
		Phonevalidate phonevalidate = criteriaBaseDao.queryCriteriaListUnique(Phonevalidate.class, criterion);

		if (phonevalidate != null) {
			phonevalidate.setValidateNum(validateCode); // 更新状态
			phonevalidate.setIsValid(1); // 设置验证码生效
			if (phonevalidate.getValidateCodeNumber() == null) { // 未设置过验证次数，初始化为0
				phonevalidate.setValidateCodeNumber(0);
			}
		} else {
			try {
				criteriaBaseDao.save(createPhoneValidate(telPhone, validateCode));
			} catch (Exception e) {
				log.error("保存手机验证码对象出现异常！", e);
				return false;
			}
		}

		return true;

	}

	/**
	 * 
	 * 创建手机验证码保存对象
	 * 
	 * @Title: createPhoneValidate 
	 * @param telPhone 手机号
	 * @param validateCode  验证码
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	private Phonevalidate createPhoneValidate(String telPhone, String validateCode) {

		Phonevalidate phonevalidate = new Phonevalidate();
		phonevalidate.setVid(UUID.randomUUID().toString());
		phonevalidate.setPhoneNum(telPhone); // 手机号
		phonevalidate.setValidateCodeNumber(0);// 验证次数
		phonevalidate.setValidateNum(validateCode); // 验证码
		phonevalidate.setCreateTime(new Date()); // 发送时间
		phonevalidate.setIsValid(1); // 有效
		return phonevalidate;

	}

}
